﻿using Nancy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy.ModelBinding;
using Nancy.Extensions;
using Nancy.Authentication.Forms;
using NancyOauth2.Domains;
using NancyOauth2.Models;

namespace NancyOauth2.Modules
{
    public class AuthModule : Nancy.NancyModule
    {
        public AuthModule(IAuthDomain authDomain) : base("/auth")
        {
            Post["token"] = _ =>
            {
                AuthErrorModel errorModel;

                string clientId = this.Request.Form.client_id;
                string clientSecret = this.Request.Form.client_secret;
                string redirectUri = this.Request.Form.redirect_uri;
                string grantType = this.Request.Form.grant_type;
                string refreshToken = this.Request.Form.refresh_token;

                if (!authDomain.CheckClientInfo(clientId, clientSecret, redirectUri, grantType,refreshToken,out errorModel))
                {
                    return Response.AsJson(errorModel);
                }
                
                return Response.AsJson(authDomain.GetToken(clientId, clientSecret, redirectUri, grantType, refreshToken)) .WithCookie("rwecho","cox");
            };
        }
    }
}